<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleTabClick" :before-leave="beforeLive">
      <el-tab-pane label="赛事管理" name="1">
        <!--查询-->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="赛事标题" prop="matchTitle" >
            <el-input
              v-model="queryParams.matchTitle"
              placeholder="请输入赛事标题"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable
                            v-model="queryParams.startTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
                            v-model="queryParams.endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="赛事状态" prop="matchStatus">
            <el-select v-model="queryParams.matchStatus" placeholder="请选择赛事状态" clearable>
              <el-option
                v-for="dict in dict.type.hd_match_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!--增删改-->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['match:matchInfo:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['match:matchInfo:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['match:matchInfo:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['match:matchInfo:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!--列表-->
        <el-row :gutter="10">
          <el-checkbox-group v-model="ids" @change="handleSelectionChange">
            <template v-for="(item,index) in matchList">

              <el-col :span="12" style="margin-bottom: 15px;">
                <el-card :body-style="{ padding: '0px'}" >
                  <div class="card-content">
                    <div style="position: absolute;right:20px;bottom:0px;">
                      <el-tag :type="item.matchStatus==1?'':item.matchStatus==2?'success':item.matchStatus==0?'info':''" effect="light">
                        {{item.matchStatus==1?'进行中':item.matchStatus==2?'已结束':item.matchStatus==0?'未开始':''}}
                      </el-tag>

                    </div>
                    <el-checkbox  :label="item.matchId"></el-checkbox>
                    <image-preview :src="item.matchImg" :width="280" :height="160" style="margin-left:5px;"/>
                    <div class="card-text">
                      <div class=""card-title>名称：{{item.matchTitle}}</div>
                      <div class=""card-url>URL：{{item.matchTemplate?item.matchTemplate.matchUrl:'未创建赛事模板'}}</div>
                      <div class=""card-personNum>报名人数：{{item.applyNum}}</div>
                    </div>
                  </div>
                  <div class="card-ctroll-wrap">
                    <div class="button" @click="handleUpdate(item)">赛事信息</div>
                    <div class="button" @click=" handleSsmb(item)">模板配置</div>
                    <div class="button"  @click="handleBdpz(item)">报名表单管理</div>
                  </div>
                </el-card>

              </el-col>
            </template>
          </el-checkbox-group>
        </el-row>
        <!--列表分页-->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          :page-sizes="[4,6,10]"
          @pagination="getList"
        />

        <!-- 添加或修改赛事管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body center>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
            <el-form-item label="赛事标题" prop="matchTitle">
              <el-input v-model="form.matchTitle" placeholder="请输入赛事标题" />
            </el-form-item>
            <el-form-item label="赛事主图"  prop="matchImg">
              <image-upload v-model="form.matchImg" :limit="1"/>
            </el-form-item>
            <el-form-item label="赛事时间">
              <el-date-picker
                v-model="datePickRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :picker-options="pickerOptions"

              >
              </el-date-picker>
            </el-form-item>


            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" round>确 定</el-button>
            <el-button @click="cancel" round>取 消</el-button>
          </div>
        </el-dialog>

        <!-- 赛事模板配置 -->
        <el-dialog :title="shmbFormtitle" :visible.sync="shmbopen" width="50%" append-to-body center>
          <el-form ref="shmbForm" :model="shmbForm" :rules="shmbrules" label-width="100px">
            <el-form-item label="URL" prop="matchUrl">
              <el-input v-model="shmbForm.matchUrl" placeholder="请输入模板链接" />
            </el-form-item>
            <el-form-item label="logo"  prop="matchLogo">
              <image-upload v-model="shmbForm.matchLogo" :limit="1" :fileSize="100/1000" :fileType="['ico']"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="shmbSubmitForm" round>确 定</el-button>
            <el-button @click="shmbCancel" round>取 消</el-button>
          </div>
        </el-dialog>

      </el-tab-pane>
      <el-tab-pane label="表单配置" name="2">
        <bmbdpz :ssInfo="ssInfo"  ref="bmbdpz"/>
      </el-tab-pane>

    </el-tabs>

  </div>
</template>

<script>
import { listMatch, getMatch, delMatch, addMatch, updateMatch } from "@/api/match/matchInfo";
import {addMatchTemplate,updateMatchTemplate} from '@/api/match/matchTemplate'
import bmbdpz from '../../../components/1myComponents/ssgl/bmbdpz'
export default {
  name: "Match",
  dicts: ['hd_match_status','hd_match_status'],
  components:{
    bmbdpz
  },
  data() {
    return {

      //赛事时间结果【不可能比建立比赛【当天】还早】
      datePickRange:[],
      //时间范围挑选最小时间
      pickMinDate:'',
      //赛事时间选择配置
      pickerOptions:{
        // onPick: ({ maxDate, minDate }) => {
        //   this.pickMinDate=minDate
        //   if(maxDate){
        //     this.pickMinDate=''
        //   }
        // },
        disabledDate: time => {
            return time.getTime() < Date.now() - 8.64e7;
          }

       },

      activeName: '1',//赛事管理和表单配置切换
      ssInfo:{},



      /**赛事木模板**/
      shmbopen:false,//赛事模板弹框
      shmbFormtitle:'',//弹框标题
      shmbForm:{},//赛事模板需传入的值
      shmbrules:{},
      /**添加赛事**/
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 赛事管理表格数据
      matchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 4,
        matchTitle: null,
        matchImg: null,
        startTime: null,
        endTime: null,
        matchStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

    };
  },
  created() {
    this.getList();
  },

  methods: {


    /*赛事模板标题开始*/
    //getBmList(){},
   beforeLive(){
      if(this.ids.length!=1) {
        this.$modal.msgWarning("请选择一条赛事配置表单")
        return false
      } else{
        //this.handleTabClick()
        return true
      }
      },





    handleTabClick(){
      let [row]=this.matchList.filter(x=>x.matchId==this.ids[0])
      this.ssInfo=row
    },
    /**表单配置**/
    handleBdpz(row){
      this.ids=[]
      this.ids.push(row.matchId)
      this.activeName='2'
      this.ssInfo=row

    },

    selectTab(tab,e){
      console.log(tab,e)
    },

    /**赛事模板**/
    //创建或者修改赛事模板
    handleSsmb(row){
      //详情模板
    /*  console.log(getNowDate())
      if(row.formVos.length>0){
        row.formVos.forEach(item=>{
         // if(item.formStatus==0&&new Date()>)
        })
      }*/
      this.shmbopen=true
      if(row.matchTemplate==null){
        this.restSsmb()
        this.shmbFormtitle='创建模板'
        this.shmbForm.matchId=row.matchId

      }else{
        this.shmbFormtitle='修改模板'
        this.restSsmb();
        this.shmbForm.matchId=row.matchId
        this.shmbForm.templateId= row.matchTemplate.templateId
        this.shmbForm.matchUrl=row.matchTemplate.matchUrl
        this.shmbForm.matchLogo=row.matchTemplate.matchLogo
      }

    },
    //创建或者更新赛事模板
    shmbSubmitForm(){
      this.$refs["shmbForm"].validate(valid => {

        if (valid) {

          if (this.shmbForm.templateId != null) {
            updateMatchTemplate(this.shmbForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.shmbopen = false;
              this.getList();
            });
          } else {
            addMatchTemplate(this.shmbForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.shmbopen = false;
              this.getList();
            });
          }
        }
      });
    },
    shmbCancel() {
      this.shmbopen = false;
      this.restSsmb();
    },
    //赛事模板表单重置
    restSsmb(){
      this.shmbForm={
        matchId: null,
        matchLogo: null,
        matchUrl: null,
        templateId: null,
      }
      this.resetForm("shmbForm");
    },
/** 赛事模板标题结束**/

//赛事时间选择
// changePick(e){
//
//     },
    //查询赛事管理列表
    getList() {
      this.loading = true;
      listMatch(this.queryParams).then(response => {
        this.matchList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.matchList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

//将时间转成字符串方法
    formatDateStr(dateP) {
  let now = new Date(dateP);
  let year = now.getFullYear();
  let month = (now.getMonth() + 1).toString().padStart(2, "0");
  let date = (now.getDate()).toString().padStart(2, "0");
  let hh = (now.getHours()).toString().padStart(2, "0");
  let mm = (now.getMinutes()).toString().padStart(2, "0");
  let ss = (now.getSeconds()).toString().padStart(2, "0");
  return `${year}-${month}-${date} ${hh}:${mm}:${ss}`;
},



    // 表单重置
    reset() {
      this.form = {
        matchId: null,
        matchTitle: null,
        matchImg: null,
        startTime: null,
        endTime: null,
        matchStatus: '1',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.single = !(this.ids.length==1)//修改是否禁用
      this.multiple = !(this.ids.length>=1)//删除是否禁用


    },
    /** 新增按钮操作 */
    handleAdd() {
      this.datePickRange=[]
      this.form.startTime=null
      this.form.endtTime=null
      this.reset();
      this.open = true;
      this.title = "添加赛事管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const matchId = row.matchId || this.ids
      getMatch(matchId).then(response => {
        this.form = response.data;
        this.datePickRange=[response.data.startTime, response.data.endTime]
        this.open = true;
        this.title = "修改赛事管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(111,this.form)
        this.form.startTime=this.formatDateStr(this.datePickRange[0])
        this.form.endTime=this.formatDateStr(this.datePickRange[1])
        console.log(222,this.form)
        if (valid) {
          if (this.form.matchId != null) {
            updateMatch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMatch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const matchIds = row.matchId || this.ids;
      this.$modal.confirm('是否确认删除赛事管理编号为"' + matchIds + '"的数据项？').then(function() {
        return delMatch(matchIds);
      }).then(() => {
        this.ids=[]
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('match/matchInfo/export', {
        ...this.queryParams
      }, `match_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.card-content{display: flex;align-items: center;font-size:14px;padding:20px 20px 0 20px;position: relative}
.card-text{display: flex;flex-direction: column;justify-content: space-between;margin:5px 0 5px 15px;height:160px;}
.card-ctroll-wrap{display: flex;border-top:1px solid #eee;border-bottom:1px solid #eee;margin:10px 0 0 0;padding:10px 0;
  font-size:14px;
  .button{width:33.333%;border-right:1px solid #eee;text-align: center}
}
::v-deep{
  .el-checkbox__label{display: none}
  .el-dialog {
    border-radius: 11px;
  }
}
</style>
